﻿using System;
using System.Text;
using System.Windows.Forms;
using SourceCodePlugin.Controls;
using WindowsLive.Writer.Api;

namespace SourceCodePlugin
{
	[WriterPlugin(
		"9EDA38F6-AE13-4003-B74A-83E8474F528D", 
		"Wordpress Sourcecode Plugin",
		Description = "A [sourcecode] plugin for Wordpress.com blogs",
		PublisherUrl = "http://meisinger2.wordpress.com/",
		ImagePath = "Images.SourceCode.ico",
		HasEditableOptions = false)]
	[InsertableContentSource("Wordpress Sourcecode Plugin")]
	public class Plugin : SmartContentSource
	{
        public override DialogResult CreateContent(IWin32Window dialogOwner, ISmartContent newContent)
        {
            try
            {
                var settings = new Settings(newContent.Properties);
                using (var editor = new SourceCodeEditor(settings))
                {
                    return editor.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                var buffer = new StringBuilder();
                buffer.Append(ex.Message);
                buffer.AppendLine();
                buffer.Append(ex.StackTrace);

                MessageBox.Show(buffer.ToString(), "Exception", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return DialogResult.OK;
            }
        }

        public override SmartContentEditor CreateEditor(ISmartContentEditorSite editorSite)
        {
            return new SettingsEditor();
        }

        public override string GenerateEditorHtml(ISmartContent content, IPublishingContext publishingContext)
        {
            content.Layout.Alignment = Alignment.Center;

            var settings = new Settings(content.Properties);
            return string.Format("<pre style=\"width:100%;background-color:#f4f4f4;border:solid 1px #c0c0c0;\">{0}</pre>", 
                HtmlServices.HtmlEncode(settings.Code));
        }

        public override string GeneratePublishHtml(ISmartContent content, IPublishingContext publishingContext)
        {
            var settings = new Settings(content.Properties);
            return string.Format("<pre>[sourcecode language=\"{0}\"]{1}[/sourcecode]</pre>",
                settings.Language, settings.Code);
        }
    }
}
